package com.llkj.qingnianguoxue.home;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.BookDetailRecommendAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.BookDetailBean;
import com.llkj.qingnianguoxue.bean.HotRankingBean;
import com.llkj.qingnianguoxue.bean.ResponseBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.mine.PayOrderActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.DownloadFilesService;
import com.llkj.qingnianguoxue.util.GridSpacingItemDecoration;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.MyShare;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.view.ReadActivity;
import com.pingplusplus.android.Pingpp;
import com.tbruyelle.rxpermissions.RxPermissions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

import static com.llkj.qingnianguoxue.mine.PayOrderActivity.REQUEST_ORDER_PAY;
import static com.llkj.qingnianguoxue.view.ReadActivity.REQUEST_READ_BOOK_CODE;

/**
 * 图书详情
 */
public class BookDetailActivity extends BaseActivity implements View.OnClickListener,MyShare.ShareResultCallback{
    private static final int REQUEST_CART_CODE = 8974;
    private static final int REQUEST_LOGIN_CODE = 8975;
    private NestedScrollView nestedScrollView;
    private RelativeLayout flTitle;
    private View titleViewBg;
    private ImageView ivBack, ivShare;//返回，分享
    private TextView tvVedioTitle, tvCount, tvRecommendPerson;//视频题目，报名人数,推荐人
    private ImageView ivBookPic;//图片

    private LinearLayout llRecommend;//推荐
    private WebView wvDescription;//图书描述
    private RecyclerView lvRecommned;//推荐列表
    private BookDetailRecommendAdapter recommendAdapter;
    private List<HotRankingBean.RankingBean> mRankData;

    private FrameLayout rlBottom;
    private TextView tvBuy;//加入购物车、购买
    private String mDetailId, mCartId;//图示id，购物车id
    private String mPayMoney;//支付金额
    private boolean isAddCart = false;//false未加入
    private int mShopCount;//购物车
    private boolean isResult;//控制是否返回
    private String mCorverUrl, mDescription, mBookFileUrl;//图书封面url,图书链接url

    private BookDetailBean bookDetailBean;
    @BindView(R.id.tv_read_free)
    public TextView tvReadFree;//免费试读
    @BindView(R.id.tv_add_cart)
    public TextView tvAddCart;//加入购物车
    private HotRankingBean.RankingBean mBookBean;//保存图书信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_detail);
        ButterKnife.bind(this);

//        systemBarTintManager.setStatusBarTintResource(R.color.transparent);
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                    }
                });

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mDetailId = bundle.getString("id");
        }

        initView();

        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,flTitle,R.color.gray_bar);
        initListener();

        loadWaitDialog();
        getBookDetail();
    }

    private void initView() {
        nestedScrollView = (NestedScrollView) findViewById(R.id.scrollView);
        nestedScrollView.setVisibility(View.GONE);
        flTitle = (RelativeLayout) findViewById(R.id.rl_top_title);
        titleViewBg = findViewById(R.id.title_view_bg);
        ivBookPic = (ImageView) findViewById(R.id.iv_book_pic);

        ivBack = (ImageView) findViewById(R.id.iv_back);//返回，分享
        ivShare = (ImageView) findViewById(R.id.iv_share);
        tvVedioTitle = (TextView) findViewById(R.id.tv_title);//视频题目，报名人数
        tvCount = (TextView) findViewById(R.id.tv_count);
        tvRecommendPerson = (TextView) findViewById(R.id.tv_recommend_person);//推荐人

        llRecommend = (LinearLayout) findViewById(R.id.ll_book_recommend);

        wvDescription = (WebView) findViewById(R.id.webView);
        setWebview();

        lvRecommned = (RecyclerView) findViewById(R.id.lv_recommend);
        GridLayoutManager mgr = new GridLayoutManager(this, 4);
        lvRecommned.setLayoutManager(mgr);
        lvRecommned.addItemDecoration(new GridSpacingItemDecoration(4, 10, false));
        lvRecommned.setFocusable(false);

        mRankData = new ArrayList<>();
        recommendAdapter = new BookDetailRecommendAdapter(R.layout.item_jing_xuan_vedio2, mRankData);
        lvRecommned.setAdapter(recommendAdapter);

        rlBottom = (FrameLayout) findViewById(R.id.fl_bottom);
        rlBottom.setVisibility(View.GONE);
        tvBuy = (TextView) findViewById(R.id.tv_pay);
        tvBuy.setSelected(true);

    }

    /**
     * 设置WebView
     */
    private void setWebview() {
        WebSettings settings = wvDescription.getSettings();
        //支持javascript
        settings.setJavaScriptEnabled(true);
        //自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);

        String webUrl = String.format(HttpMethod.ARTIST_DETAILS_ABSTRACT,mDetailId,"2");
        wvDescription.loadUrl(webUrl);
    }

    private void initListener() {
        ivBack.setOnClickListener(this);
        ivShare.setOnClickListener(this);
        tvBuy.setOnClickListener(this);

        lvRecommned.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                HotRankingBean.RankingBean item = mRankData.get(i);
                Bundle bundle = new Bundle();
                bundle.putString("id", item.getId());
                startActivity(BookDetailActivity.class, bundle);
            }
        });
    }

    @OnClick({R.id.tv_read_free, R.id.tv_add_cart})
    public void onClickView(View v){
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        switch (v.getId()){
            case R.id.tv_add_cart://加入购物车
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                if (!isAddCart) {
                    addCart();
                } else {
                    delCart();
                }
                break;
            case R.id.tv_read_free://免费试读
                if(bookDetailBean==null || bookDetailBean.getBooks()==null){
                    ToastUtil.makeLongText(this,"对不起，图书信息有误,不能试读");
                    return;
                }
                Intent intent = new Intent(this, ReadActivity.class);
                intent.putExtra("bookurl",mBookFileUrl);
                intent.putExtra("bookid",bookDetailBean.getBooks().getId());
                intent.putExtra("bookname",bookDetailBean.getBooks().getTitle());
                intent.putExtra("bookDesc",bookDetailBean.getBooks().getShare());
                intent.putExtra("bookCoverUrl",bookDetailBean.getBooks().getImg());
                intent.putExtra("bookbegin",0);
                intent.putExtra("payMoney",mPayMoney);
                intent.putExtra("isBuy",bookDetailBean.getBooks().getIs_buy());
                startActivityForResult(intent,REQUEST_READ_BOOK_CODE);
                break;
        }
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivityForResult(LoginActivity.class, new Bundle(), REQUEST_LOGIN_CODE);
    }

    @Override
    public void onClick(View v) {
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);

        switch (v.getId()) {
            case R.id.iv_back://返回
                finishActivity();
                finish();
                break;
            case R.id.iv_share://分享
                String videoTitle = tvVedioTitle.getText().toString();
                String linkUrl = String.format(HttpMethod.SHARE_BOOK, mDetailId);
                DialogUtil.showShareDialog(this, videoTitle, mDescription, mCorverUrl, linkUrl, this);
                break;
            case R.id.tv_pay://购买
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                if (tvBuy.isSelected()) {
                    return;
                }
                startPay();
                break;
        }
    }

    private void startPay(){
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        List<HotRankingBean.RankingBean> checkShopsData = new ArrayList<>();
        checkShopsData.add(mBookBean);
        Bundle bundle = new Bundle();
        bundle.putSerializable("checkShops", (Serializable) checkShopsData);
        bundle.putString("shopsId",mDetailId);
        bundle.putString("categoryType","BookDetail");
        try {
            bundle.putFloat("payMoney",Float.parseFloat(mPayMoney));
        }catch (Exception e){}
        startActivityForResult(PayOrderActivity.class, bundle, REQUEST_ORDER_PAY);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CART_CODE) {//从购物车返回

        } else if (resultCode == RESULT_OK && requestCode == REQUEST_LOGIN_CODE) {//登录
            getBookDetail();
        }else if(resultCode == RESULT_OK && requestCode == REQUEST_READ_BOOK_CODE){//试读界面
            setBuyState();
        }else if(resultCode == RESULT_OK && REQUEST_ORDER_PAY == requestCode){//支付成功
            setBuyState();
            String bookName = tvVedioTitle.getText().toString();
            if (!StringUtils.isEmpty(bookName) && !StringUtils.isEmpty(mBookFileUrl)) {//下载图书
                Intent serviceDownload = new Intent(this, DownloadFilesService.class);
                serviceDownload.putExtra("bookName", bookName);
                serviceDownload.putExtra("bookFile", mBookFileUrl);
                startService(serviceDownload);
            }
        }
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_HANDPICK_BOOKS_DETAILS) {//图书详情
            bookDetailBean = GsonUtil.GsonToBean(data, BookDetailBean.class);
            if (bookDetailBean != null) {
                nestedScrollView.setVisibility(View.VISIBLE);
                rlBottom.setVisibility(View.VISIBLE);
                mBookBean = new HotRankingBean.RankingBean();
                mBookBean.setType(2);
                mBookBean.setId(bookDetailBean.getBooks().getId());
                mBookBean.setTitle(bookDetailBean.getBooks().getTitle());
                mBookBean.setImg(bookDetailBean.getBooks().getImg());
                mBookBean.setAbstractX(bookDetailBean.getBooks().getShare());

                mBookFileUrl = bookDetailBean.getBooks().getFile();
                mDescription = bookDetailBean.getBooks().getShare();
                mCorverUrl = bookDetailBean.getBooks().details_file;
                ImageLoadingUtil.loadingUrl(ivBookPic, mCorverUrl);

                if (StringUtils.isEmpty(mCorverUrl)) {
                    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) nestedScrollView.getLayoutParams();
                    params.topMargin = DisplayUtil.dip2px(this, 45);
                    ivShare.setImageResource(R.drawable.icon_video_share);
                    titleViewBg.setAlpha(1);
                    ivBookPic.setVisibility(View.GONE);
                }/*else{
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ivBookPic.getLayoutParams();
                    params.height = DisplayUtil.getDensityWdith(this)*500/750;
                }*/
                tvVedioTitle.setText(bookDetailBean.getBooks().getTitle());//视频题目
                String score = bookDetailBean.getBooks().getOrder_num() + "人购买";
                tvCount.setText(score);
                tvRecommendPerson.setText("推荐人-" + bookDetailBean.getBooks().getReferrer());//推荐人
                mShopCount = Integer.parseInt(bookDetailBean.getNum());

                if (bookDetailBean.getBooks().getIs_buy() == 1) {////是1否,隐藏加入和购买按钮
                    setBuyState();
                } else {
                    mPayMoney = bookDetailBean.getBooks().getPrice();
                    tvBuy.setText("购买:￥" + mPayMoney);
                    tvBuy.setSelected(false);

                    if (!StringUtils.isEmpty(bookDetailBean.getBooks().getShopping_id())) {
                        tvAddCart.setText("移除购物车");
                        mCartId = bookDetailBean.getBooks().getShopping_id();
                        isAddCart = true;
                    }
                }

                if (bookDetailBean.getHot() != null) {
                    mRankData.clear();
                    mRankData.addAll(bookDetailBean.getHot());
                    recommendAdapter.notifyDataSetChanged();
                }
            }
        } else if (method == HttpMethod.HTTP_ORDER_ADD_SHOPPING) {//9.2视频/图书加购物车
            ResponseBean responseBean = GsonUtil.GsonToBean(data, ResponseBean.class);
            if (responseBean != null) {
                ToastUtil.makeLongText(this, "成功加入购物车");
                tvAddCart.setText("移除购物车");
                mShopCount++;
                isAddCart = true;
                mCartId = responseBean.getShopping_id();
                isResult = !isResult;
                setResult(RESULT_OK);
            }
        } else if (method == HttpMethod.HTTP_USER_DEL_SHOPPING) {//8.13删除购物车商品
            ToastUtil.makeLongText(this, "成功移除购物车");
            tvAddCart.setText("加入购物车");
            mShopCount--;
            isAddCart = false;
            mCartId = null;
            isResult = !isResult;
            setResult(RESULT_OK);
        } else if (method == HttpMethod.HTTP_YOUR_URL) {//获取支付参数
            try {
                JSONObject jsonObject = new JSONObject(data);
                if (jsonObject.has("error")) {
                    jsonObject = jsonObject.getJSONObject("error");
                    String message = jsonObject.getString("message");
                    dialogPrompt(message, null, "知道了").show();
                } else {
                    Pingpp.createPayment(this, data);//调起支付控件
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (method == HttpMethod.HTTP_ORDER_ORDER_VIDEO) {//9.3 购买图书/视频
            setBuyState();
            String bookName = tvVedioTitle.getText().toString();
            if (!StringUtils.isEmpty(bookName) && !StringUtils.isEmpty(mBookFileUrl)) {//下载图书
                Intent serviceDownload = new Intent(this, DownloadFilesService.class);
                serviceDownload.putExtra("bookName", bookName);
                serviceDownload.putExtra("bookFile", mBookFileUrl);
                startService(serviceDownload);
            }
        }
    }

    private void setBuyState(){
        if(null!=bookDetailBean) {
            bookDetailBean.getBooks().setIs_buy(1);
        }
        tvBuy.setSelected(true);
        tvAddCart.setVisibility(View.GONE);
        tvBuy.setVisibility(View.GONE);
        tvReadFree.setText("阅读");
        setResult(RESULT_OK);
    }

    @Override
    public void shareResultCallBack(int result) {
        switch (result) {
            case 1:
                HttpMethod.pubShare(this,this,mDetailId,"1");
                break;
            case 2:
                break;
            case 3:
                break;
        }
    }

    /**
     * 获取图书详情
     */
    private void getBookDetail() {
        HttpMethod.handpicBookDetails(this, this, mDetailId);
    }

    /**
     * 加入购物车
     */
    private void addCart() {
//        loadWaitDialog();
        HttpMethod.addShopping(this, this, "2", mDetailId);
    }

    /**
     * 删除购物车
     */
    private void delCart() {
        if (!StringUtils.isEmpty(mCartId)) {
//            loadWaitDialog();
            HttpMethod.delShopping(this, this, mCartId,"2");
        }
    }

    /**
     * 結束当前界面
     */
    private void finishActivity() {
        if (isResult) {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishActivity();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void showMsg(String title, String msg1, String msg2) {
        String str = title;
        if (null != msg1 && msg1.length() != 0) {
            str += "\n" + msg1;
        }
        if (null != msg2 && msg2.length() != 0) {
            str += "\n" + msg2;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(str);
        builder.setTitle("提示");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.create().show();
    }
}
